package com.ilibrary.web.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.ilibrary.base.MyAjaxAction;
import com.ilibrary.base.MyBaseVO;
import com.ilibrary.constants.MyConstants;
import com.ilibrary.constants.MyMsgConstants;
import com.ilibrary.service.BookService;
import com.ilibrary.service.BorrowService;
import com.ilibrary.utils.MyColumnIndicator;
import com.ilibrary.utils.MyTools;
import com.ilibrary.web.dto.ResultDto;
import com.ilibrary.web.vo.AdminVO;
import com.ilibrary.web.vo.BookVO;
import com.ilibrary.web.vo.BorrowVO;
import com.opensymphony.xwork2.Result;

public class DoReturnBorrowAction extends MyAjaxAction {

	private BorrowService borrowService;
	private BookService bookService;
	
	public BorrowService getBorrowService() {
		return borrowService;
	}
	public void setBorrowService(BorrowService borrowService) {
		this.borrowService = borrowService;
	}
	public BookService getBookService() {
		return bookService;
	}
	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}
	
	@Override
	protected JSONObject doExecute(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		String bookId = request.getParameter("bookId");
		JSONObject jo = new JSONObject();
		
		AdminVO adminVO = (AdminVO) session.getAttribute(MyConstants.ILIBRARY_LOGIN_ADMIN);
		
		ResultDto<BorrowVO> resultDto = borrowService.findByBookId(bookId);
		if(!resultDto.isSuccess()) {
			jo.put("success", false);
			jo.put("msg", resultDto.getMsg());
			return jo;
		}
		
		BorrowVO borrowVO = resultDto.getFirstResult();
		Date nowDate = new Date();
		logger.info(MyTools.getDayBetweenTwoDate(borrowVO.getBorrowDeadline(), nowDate));
		if(MyTools.getDayBetweenTwoDate(borrowVO.getBorrowDeadline(), nowDate) < 0) {
			jo.put("success", false);
			jo.put("msg", MyMsgConstants.BORROW_IS_OVERDUE);
			return jo;
		}else {
			Date date = new Date();
			
			ResultDto<BookVO> resultDtoBookVO = bookService.findById(borrowVO.getBookId());
			BookVO bookVO = resultDtoBookVO.getFirstResult();
			bookVO.setBookStatus(MyColumnIndicator.BOOK_STATUS_IN_LIB);
			bookVO.setUpdateDt(date);
			bookVO.setUpdateUser(adminVO.getAdminId());
			ResultDto<MyBaseVO> dto = bookService.update(bookVO);
			
			borrowVO.setBorrowStatus(MyColumnIndicator.BORROW_STATUS_COMPLETE);
			borrowVO.setUpdateDt(date);
			borrowVO.setUpdateUser(adminVO.getAdminId());
			ResultDto<MyBaseVO> resultDto2 = borrowService.update(borrowVO);
		}
		jo.put("success", true);
		return jo;
	}

}
